package com.zhongxi.guoyuan.view.beautifulStore;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.beautifulStore.BeautifulStoreAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.beautifulStore.BeautifulStoreData;
import com.zhongxi.guoyuan.entity.beautifulStore.BeautifulStoreResult;
import com.zhongxi.guoyuan.entity.beautifulStore.ServiceInfoResult;
import com.zhongxi.guoyuan.entity.subscribe.SubscribeResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.GlideRoundTransform;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.view.user.LoginActivity;
import com.zhongxi.guoyuan.widget.CustomDatePicker;
import com.zhongxi.guoyuan.widget.sliding.NoScrollListView;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SubscribeActivity extends BaseActivity implements View.OnClickListener, TextWatcher {

    private TextView goService;
    private TextView backService;
    private CustomDatePicker datePicker;
    private NumberPicker numPicker;
    private NoScrollListView lvList;
    private BeautifulStoreAdapter adapter;
    private RelativeLayout relaGo;
    private RelativeLayout relaStore;
    private EditText etTips;
    private TextView tvNum;
    private TextView tvOrder;
    private int flag = 2;
    private Map<String, String> map = new HashMap<String, String>();
    private String id;
    private String mytime;
    private EditText etPhone;
    private EditText etAddress;
    private String type;
    private TextView tvTime;
    private ImageView ivImg;
    private TextView tvProjectName;
    private TextView tvBeautiful;
    private TextView tvCash;
    private TextView tvBack;
    private BeautifulStoreResult result;
    private List<BeautifulStoreData> data = new ArrayList<>();

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_subscribe);
        initTitle();
        tvTitle.setText("预约确认");

        id = getIntent().getStringExtra("id");

        ivImg = (ImageView) findViewById(R.id.ivImg);
        tvProjectName = (TextView) findViewById(R.id.tvProjectName);
        tvBeautiful = (TextView) findViewById(R.id.tvBeautiful);
        tvCash = (TextView) findViewById(R.id.tvCash);
        tvBack = (TextView) findViewById(R.id.tvBack);
        tvTime = (TextView) findViewById(R.id.tvTime);

        goService = (TextView) findViewById(R.id.goService);
        backService = (TextView) findViewById(R.id.backService);
        backService.setSelected(true);

        etTips = (EditText) findViewById(R.id.etTips);
        tvNum = (TextView) findViewById(R.id.tvNum);
        tvOrder = (TextView) findViewById(R.id.tvOrder);

        relaGo = (RelativeLayout) findViewById(R.id.relaGo);
        relaStore = (RelativeLayout) findViewById(R.id.relaStore);
        lvList = (NoScrollListView) findViewById(R.id.lvList);

        etPhone  = (EditText) findViewById(R.id.etPhone);
        etAddress = (EditText) findViewById(R.id.etAddress);

        datePicker = (CustomDatePicker) findViewById(R.id.datePicker);
        datePicker.setDividerColor(0xffcccccc);
        datePicker.setPickerMargin(10);
        numPicker = (NumberPicker) findViewById(R.id.numPicker);
        numPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                mytime = newVal+":00";
            }
        });
        String[] time = new String[24];
        for(int i = 0; i<24; i++){
            time[i] = i+":00";
        }
        numPicker.setDisplayedValues(time);
        numPicker.setMinValue(0);
        numPicker.setMaxValue(time.length-1);
        numPicker.setValue(8);
        mytime = "8:00";

        Field pf = null;
        try {
            pf =NumberPicker.class.getDeclaredField("mSelectionDivider");
            pf.setAccessible(true);
            pf.set(numPicker, new ColorDrawable(getResources().getColor(R.color.text_hint_color)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new BeautifulStoreAdapter(context, data);
        lvList.setAdapter(adapter);
        type = "serviceInfo";
        String str = "&sid="+id;
        getServer(Url.SERVICE, null, str, false, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        goService.setOnClickListener(this);
        backService.setOnClickListener(this);
        etTips.addTextChangedListener(this);
        ivBack.setOnClickListener(this);
        tvOrder.setOnClickListener(this);
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.setTemp(position);
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("serviceInfo".equals(type)){
                ServiceInfoResult serviceInfoResult = gson.fromJson(response, ServiceInfoResult.class);
                if(null!=serviceInfoResult.getSafeobj()&&!"".equals(serviceInfoResult.getSafeobj()))
                    MyApplication.getInstance().setSpValue(serviceInfoResult.getSafeobj());
                if(null!=serviceInfoResult.getData()&&!"".equals(serviceInfoResult.getData())){
                    initInfo(serviceInfoResult.getData());
                }
                getStore();
            }else if("shoplist".equals(type)){
                result = gson.fromJson(response, BeautifulStoreResult.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj()))
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                if(pageNum == 1){
                    data.clear();
                }
                if(null!=result.getData()&&!"".equals(result.getData())){
                    data.addAll(result.getData());
                }
                adapter.notifyDataSetChanged();
            }else if("addsubscribe".equals(type)){
                SubscribeResult subscribeResult = gson.fromJson(response, SubscribeResult.class);
                if(null!=subscribeResult.getSafeobj()&&!"".equals(subscribeResult.getSafeobj()))
                    MyApplication.getInstance().setSpValue(subscribeResult.getSafeobj());
                Intent intent = new Intent(context, OrderActivity.class);
                intent.putExtra("orderid",subscribeResult.getOrderid());
                startActivity(intent);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try{
            BaseResponse res = gson.fromJson(response, BaseResponse.class);
            if(null!=res.getSafeobj()&&!"".equals(res.getSafeobj())){
                MyApplication.getInstance().setSpValue(res.getSafeobj());
            }
            if(res.getCode()==1001){
                showShortToast("用户未登录，请先登录");
            }else if(res.getCode()==1032){
                showShortToast("此类项目限次24次/年，已预约满，不可再预约，请选择其他项目！");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void getStore() {
        type = "shoplist";
        getServer(Url.SHOP_LIST, null,"&page="+pageNum, false, null, "get");
    }

    /**
     * 初始化服务信息
     * @param data
     */
    private void initInfo(ServiceInfoResult.ServiceData data) {
        if(null!=data.getImages()&&!"".equals(data.getImages())&&data.getImages().size()>0){
            Glide.with(context).load(Url.IMG_URL+data.getImages().get(0)).placeholder(R.mipmap.iv_eg).transform(new GlideRoundTransform(context, 20)).into(ivImg);
        }
        if(null!=data.getName()&&!"".equals(data.getName())){
            tvProjectName.setText(data.getName());
        }else{
            tvProjectName.setText("");
        }
//        if(null!=data.getInnerprice()&&!"".equals(data.getInnerprice())){
//            tvBeautiful.setText(data.getInnerprice());
//        }else{
//            tvBeautiful.setText("");
//        }
        if(null!=data.getPrice()&&!"".equals(data.getPrice())){
            tvCash.setText(data.getPrice()+"元");
            tvBack.setText("[权益会员返"+new BigDecimal(data.getPrice()).multiply(new BigDecimal(data.getBacksilverratio())).intValue()/100+"银币]");
        }else{
            tvCash.setText("*元");
            tvBack.setText("[权益会员返*银币]");
        }
        if(null!=data.getServicetime()&&!"".equals(data.getServicetime())){
            tvTime.setText(data.getServicetime()+"分钟");
        }else{
            tvTime.setText("");
        }
    }


    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.ivBack:
                finish();
                break;
            case R.id.goService:
                flag = 1;
                goService.setSelected(true);
                backService.setSelected(false);
                relaGo.setVisibility(View.VISIBLE);
                relaStore.setVisibility(View.GONE);
                break;
            case R.id.backService:
                flag = 2;
                goService.setSelected(false);
                backService.setSelected(true);
                relaGo.setVisibility(View.GONE);
                relaStore.setVisibility(View.VISIBLE);
                break;
            case R.id.tvOrder:
                if(null!=MyApplication.getInstance().getUserId()&&!"".equals(MyApplication.getInstance().getUserId())){
                    gosubscribe();
                }else{
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.putExtra("position", 1);
                    startActivityForResult(intent, 102);
                }
                break;
        }
    }

    private void gosubscribe() {
        String date = datePicker.getDate()+" "+mytime;
        if(adapter.getTemp()== -1 && flag == 2){
            showShortToast("请先选择美容院");
        }else if(!checkTime(date)){
            showShortToast("预约时间不能小于当前时间");
        }else if(flag == 2){
            map.clear();
            map.put("sid",id);
            map.put("type", flag+"");
            map.put("time",date);
            map.put("shopid", data.get(adapter.getTemp()).getId());
            getData(map);
        }else if(flag == 1){
            String phone = etPhone.getText().toString().trim();
            String address = etAddress.getText().toString().trim();
            String msg = etTips.getText().toString().trim();
            if("".equals(phone)){
               showShortToast("手机号不能为空");
            }else if("".equals(address)){
                showShortToast("请输入详细地址");
            }else if(msg.length()>200){
                showShortToast("留言最多输入200个字");
            }else {
                map.clear();
                map.put("sid",id);
                map.put("type", flag+"");
                map.put("time",date);
                map.put("mphone", MyApplication.getInstance().descsc(phone));
                map.put("address", address);
                map.put("msg",msg);
                getData(map);
            }
        }
    }

    /**
     * 检查时间
     */
    private boolean checkTime(String mytime){
        boolean flag = false;
        try{
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String currentTime = sdf.format(date);
            long time = sdf.parse(currentTime).getTime();
            long selectTime = sdf.parse(mytime).getTime();

            Log.i("time",time+"");
            Log.i("time", selectTime+"");
            if(selectTime>time){
                flag = true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 添加预约
     * @param map
     */
    private void getData(Map<String, String> map) {
        type = "addsubscribe";
        getServer(Url.ADD_SUBSCRIBE, map, "", false, null, "post");
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable content) {
        MyTextUtils.TextChangeUtils(context, tvNum, content);
    }
}
